<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-tasks"></i>
              Jenkins项目管理
            </h1>
            <p class="page-subtitle">管理Jenkins任务和构建配置</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ (jobs || []).length }}</div>
              <div class="stat-label">任务总数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ (jobs || []).filter(j => j.enabled).length }}</div>
              <div class="stat-label">启用任务</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ (jobs || []).filter(j => j.last_build?.result === 'SUCCESS').length }}</div>
              <div class="stat-label">成功构建</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 工具栏：操作按钮 + 搜索过滤 -->
      <div class="search-filters glass-effect">
        <div class="toolbar-left">
          <el-button type="primary" @click="refreshJobs" class="glass-button refresh-button" :loading="loading">
            <i class="fa fa-refresh"></i>
            刷新任务
          </el-button>
          <el-button @click="syncJobs" class="glass-button sync-button" :loading="syncing">
            <i class="fa fa-sync"></i>
            同步任务
          </el-button>
          <el-button @click="showCreateModal" class="glass-button add-button">
            <i class="fa fa-plus"></i>
            创建任务
          </el-button>
          <el-button @click="exportJobs" class="glass-button import-button">
            <i class="fa fa-download"></i>
            导出任务
          </el-button>
        </div>

        <div class="toolbar-right">
          <div class="search-group">
            <input
              v-model="searchText"
              type="text"
              class="glass-input"
              placeholder="搜索Jenkins任务名称..."
            />
          </div>

          <div class="filter-group">
            <el-select v-model="selectedProject" @change="onProjectChange" class="glass-select" placeholder="所有项目">
              <el-option value="" label="所有项目" />
              <el-option v-for="project in projects" :key="project.id" :value="project.id" :label="project.name" />
            </el-select>
          </div>

          <div class="filter-group">
            <el-select v-model="selectedEnvironment" @change="onEnvironmentChange" class="glass-select" placeholder="所有环境">
              <el-option value="" label="所有环境" />
              <el-option v-for="env in environments" :key="env.id" :value="env.id" :label="env.name" />
            </el-select>
          </div>

          <div class="filter-group">
            <el-select v-model="selectedServer" @change="onServerChange" class="glass-select" placeholder="所有服务器">
              <el-option value="" label="所有服务器" />
              <el-option v-for="server in jenkinsServers" :key="server.id" :value="server.id" :label="server.name" />
            </el-select>
          </div>

          <div class="filter-group">
            <el-select v-model="selectedJobType" @change="onJobTypeChange" class="glass-select" placeholder="所有类型">
              <el-option value="" label="所有类型" />
              <el-option value="freestyle" label="Freestyle" />
              <el-option value="maven" label="Maven" />
              <el-option value="pipeline" label="Pipeline" />
            </el-select>
          </div>
        </div>
      </div>

      <!-- 任务网格 -->
      <div class="jobs-grid">
        <div
          v-for="job in filteredJobs"
          :key="job.id"
          class="job-card"
          :class="getJobStatusClass(job.last_build_status)"
        >
          <div class="job-header">
            <div class="job-info">
              <h3 class="job-name">{{ job.name }}</h3>
              <p class="job-description">{{ job.description || '暂无描述' }}</p>
            </div>
            <div class="job-badges">
              <span class="badge project-badge">{{ job.project_name || '未分配' }}</span>
              <span
                class="badge env-badge"
                :class="getEnvClass(job.environment_code)"
              >
                {{ job.environment_name || '未分配' }}
              </span>
              <span
                class="badge type-badge"
                :class="getJobTypeClass(job.job_type)"
              >
                {{ getJobTypeText(job.job_type) }}
              </span>
            </div>
          </div>

          <div class="job-details">
            <div class="detail-row">
              <span class="label">Jenkins服务器:</span>
              <span class="value">{{ job.jenkins_server_name || '未知' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">关联仓库:</span>
              <span class="value">{{ job.gitlab_project_name || '未关联' }}</span>
            </div>
            <div class="detail-row">
              <span class="label">最后构建:</span>
              <span class="value">{{ formatDate(job.last_build_time) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">构建状态:</span>
              <span
                class="value build-status"
                :class="getBuildStatusClass(job.last_build_status)"
              >
                {{ getBuildStatusText(job.last_build_status) }}
              </span>
            </div>
          </div>

          <div class="job-actions">
            <button class="glass-button small primary" @click="triggerBuild(job)">
              <i class="fa fa-play"></i>
              构建
            </button>
            <button class="glass-button small" @click="viewBuilds(job)">
              <i class="fa fa-history"></i>
              构建历史
            </button>
            <button class="glass-button small" @click="viewLogs(job)">
              <i class="fa fa-file-text"></i>
              日志
            </button>
            <button class="glass-button small" @click="editJob(job)">
              <i class="fa fa-edit"></i>
              编辑
            </button>
            <button class="glass-button small danger" @click="deleteJob(job)">
              <i class="fa fa-trash"></i>
              删除
            </button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredJobs.length === 0" class="empty-state">
          <i class="fa fa-tasks empty-icon"></i>
          <h3>暂无任务</h3>
          <p>请先配置Jenkins服务器，然后同步任务</p>
          <button class="glass-button primary" @click="syncJobs">
            <i class="fa fa-refresh"></i>
            同步任务
          </button>
        </div>
      </div>
    </div>

    <!-- 创建/编辑任务模态框 -->
    <div v-if="modalVisible" class="modal-overlay" @click="closeModal">
      <div class="modal-content glass-container jenkins-create-modal" @click.stop>
        <!-- 第一步：选择任务类型 -->
        <div v-if="!isEdit && createStep === 1" class="job-type-selection">
          <div class="modal-header">
            <h3>
              <i class="fa fa-plus-circle"></i>
              创建新任务
            </h3>
            <button class="close-btn" @click="closeModal">
              <i class="fa fa-times"></i>
            </button>
          </div>

          <div class="type-selection-content">
            <p class="selection-hint">请选择要创建的任务类型：</p>

            <div class="job-types-grid">
              <div
                class="job-type-card"
                :class="{ active: selectedJobType === 'freestyle' }"
                @click="selectJobType('freestyle')"
              >
                <div class="type-icon">
                  <i class="fa fa-cogs"></i>
                </div>
                <h4>Freestyle项目</h4>
                <p>这是Jenkins中最灵活的项目类型，可以组合任何SCM、构建系统或构建触发器。</p>
              </div>

              <div
                class="job-type-card"
                :class="{ active: selectedJobType === 'maven' }"
                @click="selectJobType('maven')"
              >
                <div class="type-icon">
                  <i class="fa fa-coffee"></i>
                </div>
                <h4>Maven项目</h4>
                <p>专为Maven项目设计，提供Maven特定的配置选项和构建步骤。</p>
              </div>

              <div
                class="job-type-card"
                :class="{ active: selectedJobType === 'pipeline' }"
                @click="selectJobType('pipeline')"
              >
                <div class="type-icon">
                  <i class="fa fa-code-branch"></i>
                </div>
                <h4>Pipeline项目</h4>
                <p>使用Jenkinsfile定义构建流水线，支持复杂的CI/CD工作流。</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 第二步：配置任务 -->
        <div v-if="!isEdit && createStep === 2" class="job-configuration">
          <div class="modal-header">
            <h3>
              <button class="back-btn" @click="goBackToTypeSelection">
                <i class="fa fa-arrow-left"></i>
              </button>
              配置{{ getJobTypeText(selectedJobType) }}任务
            </h3>
            <button class="close-btn" @click="closeModal">
              <i class="fa fa-times"></i>
            </button>
          </div>

          <form @submit.prevent="saveJob" class="jenkins-config-form">
            <!-- 基本信息 -->
            <div class="config-section">
              <h4 class="section-title">
                <i class="fa fa-info-circle"></i>
                基本信息
              </h4>

              <div class="form-row">
                <div class="form-group">
                  <label>任务名称 *</label>
                  <input
                    v-model="form.name"
                    type="text"
                    class="glass-input"
                    placeholder="请输入任务名称"
                    required
                  />
                </div>

                <div class="form-group">
                  <label>Jenkins服务器 *</label>
                  <el-select
                    v-model="form.jenkins_server_id"
                    class="glass-select"
                    placeholder="请选择Jenkins服务器"
                    popper-class="glass-dropdown"
                    required
                  >
                    <el-option
                      v-for="server in jenkinsServers"
                      :key="server.id"
                      :value="server.id"
                      :label="server.name"
                    />
                  </el-select>
                </div>
              </div>

              <div class="form-group">
                <label>任务描述</label>
                <textarea
                  v-model="form.description"
                  class="glass-input"
                  placeholder="请输入任务描述"
                  rows="3"
                ></textarea>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label>所属项目 *</label>
                  <el-select
                    v-model="form.project_id"
                    class="glass-select"
                    placeholder="请选择项目"
                    popper-class="glass-dropdown"
                    required
                  >
                    <el-option
                      v-for="project in projects"
                      :key="project.id"
                      :value="project.id"
                      :label="project.name"
                    />
                  </el-select>
                </div>

                <div class="form-group">
                  <label>所属环境 *</label>
                  <el-select
                    v-model="form.environment_id"
                    class="glass-select"
                    placeholder="请选择环境"
                    popper-class="glass-dropdown"
                    required
                  >
                    <el-option
                      v-for="env in environments"
                      :key="env.id"
                      :value="env.id"
                      :label="env.name"
                    />
                  </el-select>
                </div>
              </div>
            </div>

            <!-- 构建保留策略 -->
            <div class="config-section">
              <h4 class="section-title">
                <i class="fa fa-history"></i>
                构建保留策略
              </h4>

              <div class="form-row">
                <div class="form-group">
                  <label>保留天数</label>
                  <input
                    v-model.number="form.config.days_to_keep"
                    type="number"
                    class="glass-input"
                    placeholder="保留构建的天数，-1表示永久保留"
                    min="-1"
                  />
                </div>

                <div class="form-group">
                  <label>保留个数</label>
                  <input
                    v-model.number="form.config.num_to_keep"
                    type="number"
                    class="glass-input"
                    placeholder="保留构建的个数，-1表示不限制"
                    min="-1"
                  />
                </div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label>构件保留天数</label>
                  <input
                    v-model.number="form.config.artifact_days_to_keep"
                    type="number"
                    class="glass-input"
                    placeholder="保留构件的天数，-1表示永久保留"
                    min="-1"
                  />
                </div>

                <div class="form-group">
                  <label>构件保留个数</label>
                  <input
                    v-model.number="form.config.artifact_num_to_keep"
                    type="number"
                    class="glass-input"
                    placeholder="保留构件的个数，-1表示不限制"
                    min="-1"
                  />
                </div>
              </div>
            </div>

            <!-- 源码管理 -->
            <div class="config-section">
              <h4 class="section-title">
                <i class="fa fa-code-branch"></i>
                源码管理
              </h4>

              <div class="form-group">
                <label>源码管理类型</label>
                <el-select
                  v-model="form.config.scm_type"
                  class="glass-select"
                  placeholder="请选择源码管理类型"
                  popper-class="glass-dropdown"
                >
                  <el-option value="none" label="无" />
                  <el-option value="git" label="Git" />
                  <el-option value="svn" label="SVN" />
                </el-select>
              </div>

              <div v-if="form.config.scm_type === 'git'" class="git-config">
                <div class="form-group">
                  <label>Git仓库URL *</label>
                  <input
                    v-model="form.config.git_url"
                    type="text"
                    class="glass-input"
                    placeholder="请输入Git仓库URL"
                    required
                  />
                </div>

                <div class="form-row">
                  <div class="form-group">
                    <label>分支</label>
                    <input
                      v-model="form.config.git_branch"
                      type="text"
                      class="glass-input"
                      placeholder="分支名称，如：main"
                    />
                  </div>

                  <div class="form-group">
                    <label>凭据ID</label>
                    <input
                      v-model="form.config.git_credentials"
                      type="text"
                      class="glass-input"
                      placeholder="Jenkins中配置的凭据ID"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- 构建触发器 -->
            <div class="config-section">
              <h4 class="section-title">
                <i class="fa fa-clock"></i>
                构建触发器
              </h4>

              <div class="trigger-options">
                <div class="form-group checkbox-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.triggers.scm_polling"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span>轮询SCM</span>
                  </label>
                  <input
                    v-if="form.config.triggers.scm_polling"
                    v-model="form.config.triggers.scm_schedule"
                    type="text"
                    class="glass-input schedule-input"
                    placeholder="如：H/5 * * * *（每5分钟检查一次）"
                  />
                </div>

                <div class="form-group checkbox-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.triggers.build_periodically"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span>定时构建</span>
                  </label>
                  <input
                    v-if="form.config.triggers.build_periodically"
                    v-model="form.config.triggers.build_schedule"
                    type="text"
                    class="glass-input schedule-input"
                    placeholder="如：0 2 * * *（每天凌晨2点）"
                  />
                </div>

                <div class="form-group checkbox-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.triggers.github_hook"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span>GitHub Hook触发</span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 构建环境 -->
            <div class="config-section">
              <h4 class="section-title">
                <i class="fa fa-cogs"></i>
                构建环境
              </h4>

              <div class="build-env-options">
                <div class="form-group checkbox-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.build_environment.delete_workspace"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span>构建前删除工作空间</span>
                  </label>
                </div>

                <div class="form-group checkbox-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.build_environment.add_timestamps"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span>为控制台输出添加时间戳</span>
                  </label>
                </div>

                <div class="form-group checkbox-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.build_environment.timeout_enabled"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span>构建超时</span>
                  </label>
                  <input
                    v-if="form.config.build_environment.timeout_enabled"
                    v-model.number="form.config.build_environment.timeout_minutes"
                    type="number"
                    class="glass-input timeout-input"
                    placeholder="超时时间（分钟）"
                    min="1"
                  />
                </div>
              </div>
            </div>

            <!-- 构建步骤 -->
            <div v-if="selectedJobType === 'freestyle'" class="config-section">
              <h4 class="section-title">
                <i class="fa fa-play"></i>
                构建步骤
              </h4>

              <div class="build-steps">
                <div
                  v-for="(step, index) in form.config.build_steps"
                  :key="index"
                  class="build-step"
                >
                  <div class="step-header">
                    <el-select
                      v-model="step.type"
                      class="glass-select step-type"
                      placeholder="选择步骤类型"
                      popper-class="glass-dropdown"
                    >
                      <el-option value="shell" label="执行Shell" />
                      <el-option value="batch" label="执行Windows批处理命令" />
                    </el-select>
                    <button
                      type="button"
                      @click="removeBuildStep(index)"
                      class="glass-button danger small"
                    >
                      <i class="fa fa-trash"></i>
                    </button>
                  </div>

                  <div class="step-content">
                    <textarea
                      v-model="step.command"
                      class="glass-input"
                      :placeholder="step.type === 'shell' ? '输入Shell命令' : '输入批处理命令'"
                      rows="4"
                    ></textarea>
                  </div>
                </div>

                <button
                  type="button"
                  @click="addBuildStep"
                  class="glass-button add-step"
                >
                  <i class="fa fa-plus"></i>
                  添加构建步骤
                </button>
              </div>
            </div>

            <!-- Maven配置 -->
            <div v-if="selectedJobType === 'maven'" class="config-section">
              <h4 class="section-title">
                <i class="fa fa-coffee"></i>
                Maven配置
              </h4>

              <div class="form-row">
                <div class="form-group">
                  <label>Maven版本</label>
                  <input
                    v-model="form.config.maven_name"
                    type="text"
                    class="glass-input"
                    placeholder="Maven版本名称，如：Maven"
                  />
                </div>

                <div class="form-group">
                  <label>POM文件</label>
                  <input
                    v-model="form.config.pom_file"
                    type="text"
                    class="glass-input"
                    placeholder="POM文件路径，如：pom.xml"
                  />
                </div>
              </div>

              <div class="form-group">
                <label>Goals和选项</label>
                <input
                  v-model="form.config.maven_goals"
                  type="text"
                  class="glass-input"
                  placeholder="如：clean compile package"
                />
              </div>

              <div class="form-group">
                <label>MAVEN_OPTS</label>
                <input
                  v-model="form.config.maven_opts"
                  type="text"
                  class="glass-input"
                  placeholder="Maven选项，如：-Xmx1024m"
                />
              </div>
            </div>

            <!-- Pipeline脚本 -->
            <div v-if="selectedJobType === 'pipeline'" class="config-section">
              <h4 class="section-title">
                <i class="fa fa-code"></i>
                Pipeline脚本
              </h4>

              <div class="form-group">
                <label>Pipeline脚本</label>
                <textarea
                  v-model="form.config.pipeline_script"
                  class="glass-input pipeline-script"
                  placeholder="输入Pipeline脚本"
                  rows="15"
                ></textarea>
              </div>
            </div>

            <!-- 构建后操作 -->
            <div class="config-section">
              <h4 class="section-title">
                <i class="fa fa-check-circle"></i>
                构建后操作
              </h4>

              <div class="form-group">
                <label>归档构件</label>
                <input
                  v-model="form.config.post_build_actions.archive_artifacts"
                  type="text"
                  class="glass-input"
                  placeholder="要归档的文件，如：target/*.jar"
                />
              </div>

              <div class="form-group">
                <label>发布JUnit测试结果</label>
                <input
                  v-model="form.config.post_build_actions.junit_results"
                  type="text"
                  class="glass-input"
                  placeholder="测试结果文件，如：target/surefire-reports/*.xml"
                />
              </div>

              <div class="form-group checkbox-group">
                <label class="checkbox-label">
                  <input
                    v-model="form.config.post_build_actions.email_notification"
                    type="checkbox"
                    class="glass-checkbox"
                  />
                  <span>邮件通知</span>
                </label>
                <input
                  v-if="form.config.post_build_actions.email_notification"
                  v-model="form.config.post_build_actions.email_recipients"
                  type="text"
                  class="glass-input email-input"
                  placeholder="收件人邮箱，多个用逗号分隔"
                />
              </div>
            </div>

            <div class="form-actions">
              <button type="button" @click="goBackToTypeSelection" class="glass-button">
                <i class="fa fa-arrow-left"></i>
                返回
              </button>
              <button type="button" @click="closeModal" class="glass-button">
                取消
              </button>
              <button type="submit" :disabled="saving" class="glass-button primary">
                <i v-if="saving" class="fa fa-spinner fa-spin"></i>
                {{ saving ? '创建中...' : '创建任务' }}
              </button>
            </div>
          </form>
        </div>

        <!-- 编辑模式 - 使用与创建模式相同的配置表单 -->
        <div v-if="isEdit" class="job-edit">
          <div class="modal-header">
            <h3>编辑Jenkins任务 - {{ getJobTypeDisplay(selectedJobType) }}</h3>
            <button class="close-btn" @click="closeModal">
              <i class="fa fa-times"></i>
            </button>
          </div>

          <!-- 使用与创建模式相同的配置表单 -->
          <div class="job-config-form">
            <!-- 基本信息 -->
            <div class="config-section">
              <h4><i class="fa fa-info-circle"></i> 基本信息</h4>
              <div class="form-row">
                <div class="form-group">
                  <label>任务名称 *</label>
                  <input
                    v-model="form.name"
                    type="text"
                    class="glass-input"
                    placeholder="请输入任务名称"
                    required
                  />
                </div>
                <div class="form-group">
                  <label>Jenkins任务名称</label>
                  <input
                    v-model="form.jenkins_job_name"
                    type="text"
                    class="glass-input"
                    placeholder="默认使用任务名称"
                  />
                </div>
              </div>

              <div class="form-group">
                <label>任务描述</label>
                <textarea
                  v-model="form.description"
                  class="glass-input"
                  placeholder="请输入任务描述"
                  rows="3"
                ></textarea>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label>所属项目 *</label>
                  <el-select v-model="form.project_id" class="glass-select" placeholder="请选择项目" required>
                    <el-option value="" label="请选择项目" />
                    <el-option v-for="project in projects" :key="project.id" :value="project.id" :label="project.name" />
                  </el-select>
                </div>
                <div class="form-group">
                  <label>部署环境 *</label>
                  <el-select v-model="form.environment_id" class="glass-select" placeholder="请选择环境" required>
                    <el-option value="" label="请选择环境" />
                    <el-option v-for="env in environments" :key="env.id" :value="env.id" :label="env.name" />
                  </el-select>
                </div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label>Jenkins服务器 *</label>
                  <el-select v-model="form.jenkins_server_id" class="glass-select" placeholder="请选择Jenkins服务器" required>
                    <el-option value="" label="请选择Jenkins服务器" />
                    <el-option v-for="server in jenkinsServers" :key="server.id" :value="server.id" :label="server.name" />
                  </el-select>
                </div>
                <div class="form-group">
                  <label>GitLab项目</label>
                  <el-select v-model="form.gitlab_project_id" class="glass-select" placeholder="请选择GitLab项目">
                    <el-option value="" label="请选择GitLab项目" />
                    <el-option v-for="project in gitlabProjects" :key="project.id" :value="project.id" :label="project.name" />
                  </el-select>
                </div>
              </div>

              <div class="form-group">
                <label class="checkbox-label">
                  <input
                    v-model="form.is_active"
                    type="checkbox"
                    class="glass-checkbox"
                  />
                  <span class="checkmark"></span>
                  启用任务
                </label>
              </div>
            </div>

            <!-- Jenkins配置表单 -->
            <div class="config-section">
              <h4><i class="fa fa-cogs"></i> Jenkins配置</h4>

              <!-- 构建保留策略 -->
              <div class="config-subsection">
                <h5>构建保留策略</h5>
                <div class="form-row">
                  <div class="form-group">
                    <label>保留天数 (-1表示永久保留)</label>
                    <input
                      v-model.number="form.config.days_to_keep"
                      type="number"
                      class="glass-input"
                      placeholder="-1"
                    />
                  </div>
                  <div class="form-group">
                    <label>保留构建数 (-1表示不限制)</label>
                    <input
                      v-model.number="form.config.num_to_keep"
                      type="number"
                      class="glass-input"
                      placeholder="-1"
                    />
                  </div>
                </div>
              </div>

              <!-- 源码管理 -->
              <div class="config-subsection">
                <h5>源码管理</h5>
                <div class="form-group">
                  <label>源码管理类型</label>
                  <el-select v-model="form.config.scm_type" class="glass-select" placeholder="请选择源码管理类型">
                    <el-option value="none" label="无" />
                    <el-option value="git" label="Git" />
                    <el-option value="svn" label="SVN" />
                  </el-select>
                </div>

                <div v-if="form.config.scm_type === 'git'" class="git-config">
                  <div class="form-group">
                    <label>Git仓库URL</label>
                    <input
                      v-model="form.config.git_url"
                      type="text"
                      class="glass-input"
                      placeholder="https://github.com/user/repo.git"
                    />
                  </div>
                  <div class="form-group">
                    <label>分支</label>
                    <input
                      v-model="form.config.git_branch"
                      type="text"
                      class="glass-input"
                      placeholder="main"
                    />
                  </div>
                </div>
              </div>

              <!-- 构建触发器 -->
              <div class="config-subsection">
                <h5>构建触发器</h5>
                <div class="form-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.triggers.scm_polling"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span class="checkmark"></span>
                    轮询SCM
                  </label>
                  <input
                    v-if="form.config.triggers.scm_polling"
                    v-model="form.config.triggers.scm_schedule"
                    type="text"
                    class="glass-input"
                    placeholder="H/5 * * * *"
                    style="margin-top: 8px;"
                  />
                </div>

                <div class="form-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.triggers.build_periodically"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span class="checkmark"></span>
                    定时构建
                  </label>
                  <input
                    v-if="form.config.triggers.build_periodically"
                    v-model="form.config.triggers.build_schedule"
                    type="text"
                    class="glass-input"
                    placeholder="0 2 * * *"
                    style="margin-top: 8px;"
                  />
                </div>
              </div>

              <!-- 构建环境 -->
              <div class="config-subsection">
                <h5>构建环境</h5>
                <div class="form-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.build_environment.delete_workspace"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span class="checkmark"></span>
                    构建前删除工作空间
                  </label>
                </div>

                <div class="form-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.build_environment.add_timestamps"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span class="checkmark"></span>
                    为控制台输出添加时间戳
                  </label>
                </div>

                <div class="form-group">
                  <label class="checkbox-label">
                    <input
                      v-model="form.config.build_environment.timeout_enabled"
                      type="checkbox"
                      class="glass-checkbox"
                    />
                    <span class="checkmark"></span>
                    构建超时
                  </label>
                  <input
                    v-if="form.config.build_environment.timeout_enabled"
                    v-model.number="form.config.build_environment.timeout_minutes"
                    type="number"
                    class="glass-input"
                    placeholder="20"
                    style="margin-top: 8px; width: 100px;"
                  />
                  <span v-if="form.config.build_environment.timeout_enabled" style="margin-left: 8px;">分钟</span>
                </div>
              </div>

              <!-- 构建步骤 -->
              <div class="config-subsection">
                <h5>构建步骤</h5>
                <div v-for="(step, index) in form.config.build_steps" :key="index" class="build-step">
                  <div class="step-header">
                    <el-select v-model="step.type" class="glass-select" style="width: 200px;" placeholder="选择构建类型">
                      <el-option value="shell" label="执行Shell" />
                      <el-option value="batch" label="执行Windows批处理" />
                    </el-select>
                    <button type="button" @click="removeBuildStep(index)" class="glass-button small danger">
                      <i class="fa fa-trash"></i>
                    </button>
                  </div>
                  <textarea
                    v-model="step.command"
                    class="glass-input"
                    placeholder="请输入构建命令"
                    rows="4"
                  ></textarea>
                </div>

                <button type="button" @click="addBuildStep" class="glass-button add-step">
                  <i class="fa fa-plus"></i>
                  添加构建步骤
                </button>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="form-actions">
              <button type="button" @click="closeModal" class="glass-button">
                <i class="fa fa-times"></i>
                取消
              </button>
              <button type="button" @click="saveJob" :disabled="saving" class="glass-button primary">
                <i v-if="saving" class="fa fa-spinner fa-spin"></i>
                <i v-else class="fa fa-save"></i>
                {{ saving ? '保存中...' : '保存更改' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 构建控制台模态框 -->
  <div v-if="consoleModalVisible" class="console-modal-overlay" @click="closeBuildConsole">
    <div class="console-modal" @click.stop>
      <!-- 控制台头部 -->
      <div class="console-header">
        <div class="console-title">
          <i class="fa fa-terminal"></i>
          <span>{{ currentBuildJob?.name }} - 构建 #{{ currentBuildNumber }}</span>
          <span class="build-status" :class="getBuildStatusClass(buildStatus)">
            {{ getBuildStatusText(buildStatus) }}
          </span>
        </div>
        <div class="console-controls">
          <button
            class="console-btn"
            :class="{ active: autoScroll }"
            @click="toggleAutoScroll"
            title="自动滚动"
          >
            <i class="fa fa-arrow-down"></i>
          </button>
          <button class="console-btn" @click="downloadConsoleLog" title="下载日志">
            <i class="fa fa-download"></i>
          </button>
          <button class="console-btn close-btn" @click="closeBuildConsole" title="关闭">
            <i class="fa fa-times"></i>
          </button>
        </div>
      </div>

      <!-- 构建信息 -->
      <div class="console-info">
        <span>开始时间: {{ buildStartTime }}</span>
        <span v-if="buildDuration > 0">持续时间: {{ Math.floor(buildDuration / 1000) }}s</span>
        <span v-else>构建中...</span>
      </div>

      <!-- 控制台输出 -->
      <div class="console-output" ref="consoleOutputRef">
        <pre v-if="consoleOutput">{{ consoleOutput }}</pre>
        <div v-else class="console-loading">
          <i class="fa fa-spinner fa-spin"></i>
          <span>正在获取构建日志...</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 构建历史模态框 -->
  <div v-if="buildsModalVisible" class="modal-overlay" @click="closeBuildsModal">
    <div class="modal glass-modal" @click.stop>
      <div class="modal-header">
        <h3>
          <i class="fa fa-history"></i>
          {{ currentJobForBuilds?.name }} - 构建历史
        </h3>
        <button class="close-btn" @click="closeBuildsModal">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <div class="modal-body">
        <div v-if="buildsLoading" class="loading-state">
          <i class="fa fa-spinner fa-spin"></i>
          <span>加载构建历史中...</span>
        </div>

        <div v-else-if="builds.length === 0" class="empty-state">
          <i class="fa fa-history empty-icon"></i>
          <h4>暂无构建记录</h4>
          <p>该任务还没有构建记录</p>
        </div>

        <div v-else class="builds-list">
          <div
            v-for="build in builds"
            :key="build.id"
            class="build-card"
          >
            <div class="build-header">
              <div class="build-number">
                <i class="fa fa-hashtag"></i>
                <span class="number-text">#{{ build.build_number }}</span>
              </div>
              <div class="build-status">
                <span class="status-badge" :class="getBuildStatusClass(build.status)">
                  <i class="fa fa-circle status-icon"></i>
                  {{ getBuildStatusText(build.status) }}
                </span>
              </div>
            </div>

            <div class="build-content">
              <div class="build-info-row">
                <div class="info-item">
                  <i class="fa fa-clock-o info-icon"></i>
                  <span class="info-label">开始时间</span>
                  <span class="info-value">{{ formatDate(build.start_time) }}</span>
                </div>
              </div>

              <div class="build-info-row" v-if="build.duration">
                <div class="info-item">
                  <i class="fa fa-hourglass-half info-icon"></i>
                  <span class="info-label">持续时间</span>
                  <span class="info-value">{{ Math.floor(build.duration / 1000) }}s</span>
                </div>
              </div>

              <div class="build-info-row">
                <div class="info-item">
                  <i class="fa fa-user info-icon"></i>
                  <span class="info-label">触发者</span>
                  <span class="info-value">{{ build.triggered_by || 'admin' }}</span>
                </div>
              </div>
            </div>

            <div class="build-actions">
              <!-- 正在构建中：显示实时控制台 -->
              <button
                v-if="build.status === 'BUILDING' || build.status === 'RUNNING'"
                class="action-btn console-btn"
                @click="openBuildConsole(currentJobForBuilds, build.build_number)"
                title="实时控制台 - 查看构建进度"
              >
                <i class="fa fa-terminal"></i>
                <span>实时控制台</span>
              </button>

              <!-- 已完成构建：显示查看日志 -->
              <button
                v-else
                class="action-btn log-btn"
                @click="viewBuildLog(currentJobForBuilds, build.build_number)"
                title="查看完整构建日志"
              >
                <i class="fa fa-file-text"></i>
                <span>日志</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 日志查看模态框 -->
  <div v-if="logModalVisible" class="modal-overlay" @click="closeLogModal">
    <div class="log-modal" @click.stop>
      <div class="log-header">
        <div class="log-title">
          <i class="fa fa-file-text"></i>
          <span>{{ currentLogBuild?.job?.name }} - 构建 #{{ currentLogBuild?.buildNumber }} 日志</span>
        </div>
        <div class="log-controls">
          <button class="log-btn" @click="downloadBuildLog" title="下载日志">
            <i class="fa fa-download"></i>
          </button>
          <button class="log-btn close-btn" @click="closeLogModal" title="关闭">
            <i class="fa fa-times"></i>
          </button>
        </div>
      </div>

      <div class="log-content">
        <div v-if="logLoading" class="log-loading">
          <i class="fa fa-spinner fa-spin"></i>
          <span>加载日志中...</span>
        </div>
        <pre v-else class="log-text">{{ logContent }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, ElOption, ElSelect } from 'element-plus'
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'

// 响应式数据
const jobs = ref([])
const projects = ref([])
const environments = ref([])
const jenkinsServers = ref([])
const gitlabProjects = ref([])
const selectedProject = ref('')
const selectedEnvironment = ref('')
const selectedServer = ref('')
const selectedJobType = ref('')
const searchText = ref('')
const modalVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const syncing = ref(false)
const loading = ref(false)

// 构建控制台相关
const consoleModalVisible = ref(false)
const currentBuildJob = ref(null)
const currentBuildNumber = ref(null)
const consoleOutput = ref('')
const buildStatus = ref('RUNNING')
const buildStartTime = ref('')
const buildDuration = ref(0)
const autoScroll = ref(true)
const consoleOutputRef = ref(null)
let consoleUpdateInterval = null

// 后台构建状态监控
const backgroundBuildChecks = new Map() // jobId -> { buildNumber, intervalId }

// 构建历史相关
const buildsModalVisible = ref(false)
const currentJobForBuilds = ref(null)
const builds = ref([])
const buildsLoading = ref(false)

// 日志查看相关
const logModalVisible = ref(false)
const currentLogBuild = ref(null)
const logContent = ref('')
const logLoading = ref(false)

// 创建任务相关状态
const createStep = ref(1) // 1: 选择类型, 2: 配置任务

const form = ref({
  id: null,
  name: '',
  description: '',
  job_type: '',
  project_id: '',
  environment_id: '',
  jenkins_server_id: '',
  gitlab_project_id: '',
  // Jenkins配置字段
  config: {
    // 通用配置
    disabled: false,
    concurrent_build: false,
    quiet_period: 5,
    retry_count: 0,

    // 构建保留策略
    days_to_keep: -1,
    num_to_keep: -1,
    artifact_days_to_keep: -1,
    artifact_num_to_keep: -1,

    // 源码管理
    scm_type: 'git', // git, svn, none
    git_url: '',
    git_branch: 'main',
    git_credentials: '',

    // 构建触发器
    triggers: {
      scm_polling: false,
      scm_schedule: '',
      build_periodically: false,
      build_schedule: '',
      upstream_projects: '',
      github_hook: false
    },

    // 构建环境
    build_environment: {
      delete_workspace: false,
      add_timestamps: false,
      timeout_enabled: false,
      timeout_minutes: 20
    },

    // 构建步骤 (根据类型不同)
    build_steps: [],

    // Maven配置
    maven_name: 'Maven',
    pom_file: 'pom.xml',
    maven_goals: 'clean compile package',
    maven_opts: '',

    // Pipeline配置
    pipeline_script: '',

    // 构建后操作
    post_build_actions: {
      archive_artifacts: '',
      junit_results: '',
      email_notification: false,
      email_recipients: ''
    }
  }
})

// 计算属性
const filteredJobs = computed(() => {
  let filtered = jobs.value || []

  if (selectedProject.value) {
    filtered = filtered.filter(job => job.project?.id == selectedProject.value)
  }

  if (selectedEnvironment.value) {
    filtered = filtered.filter(job => job.environment?.id == selectedEnvironment.value)
  }

  if (selectedServer.value) {
    filtered = filtered.filter(job => {
      const serverId = job.jenkins_server?.id || job.jenkins_server
      return serverId == selectedServer.value
    })
  }

  if (selectedJobType.value) {
    filtered = filtered.filter(job => job.job_type === selectedJobType.value)
  }

  return filtered
})

// 方法
const showCreateModal = () => {
  isEdit.value = false
  createStep.value = 1
  selectedJobType.value = ''
  resetForm()
  modalVisible.value = true
}

const resetForm = () => {
  form.value = {
    id: null,
    name: '',
    description: '',
    job_type: '',
    project_id: '',
    environment_id: '',
    jenkins_server_id: '',
    gitlab_project_id: '',
    config: {
      disabled: false,
      concurrent_build: false,
      quiet_period: 5,
      retry_count: 0,
      days_to_keep: -1,
      num_to_keep: -1,
      artifact_days_to_keep: -1,
      artifact_num_to_keep: -1,
      scm_type: 'git',
      git_url: '',
      git_branch: 'main',
      git_credentials: '',
      triggers: {
        scm_polling: false,
        scm_schedule: '',
        build_periodically: false,
        build_schedule: '',
        upstream_projects: '',
        github_hook: false
      },
      build_environment: {
        delete_workspace: false,
        add_timestamps: false,
        timeout_enabled: false,
        timeout_minutes: 20
      },
      build_steps: [],
      maven_name: 'Maven',
      pom_file: 'pom.xml',
      maven_goals: 'clean compile package',
      maven_opts: '',
      pipeline_script: '',
      post_build_actions: {
        archive_artifacts: '',
        junit_results: '',
        email_notification: false,
        email_recipients: ''
      }
    }
  }
}

const selectJobType = (type: string) => {
  selectedJobType.value = type
  form.value.job_type = type
  createStep.value = 2

  // 根据任务类型设置默认配置
  if (type === 'freestyle') {
    form.value.config.build_steps = [
      { type: 'shell', command: 'echo "Hello World"' }
    ]
  } else if (type === 'maven') {
    form.value.config.maven_goals = 'clean compile package'
    form.value.config.pom_file = 'pom.xml'
    form.value.config.maven_name = 'Maven'
  } else if (type === 'pipeline') {
    form.value.config.pipeline_script = `pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                echo '检出代码'
            }
        }

        stage('Build') {
            steps {
                echo '构建项目'
            }
        }

        stage('Test') {
            steps {
                echo '运行测试'
            }
        }

        stage('Deploy') {
            steps {
                echo '部署应用'
            }
        }
    }

    post {
        always {
            echo '构建完成'
        }
    }
}`
  }
}

// 构建步骤管理方法
const addBuildStep = () => {
  form.value.config.build_steps.push({
    type: 'shell',
    command: ''
  })
}

const removeBuildStep = (index: number) => {
  form.value.config.build_steps.splice(index, 1)
}

const goBackToTypeSelection = () => {
  createStep.value = 1
}

const editJob = (job: any) => {
  isEdit.value = true

  // 设置任务类型并进入配置步骤
  selectedJobType.value = job.job_type
  createStep.value = 2

  // 填充基本信息
  form.value = {
    id: job.id,
    name: job.name,
    description: job.description,
    job_type: job.job_type,
    project_id: job.project || '',
    environment_id: job.environment || '',
    jenkins_server_id: job.jenkins_server || '',
    gitlab_project_id: job.gitlab_project_id || '',
    jenkins_job_name: job.jenkins_job_name || job.name,
    is_active: job.is_active !== undefined ? job.is_active : true,

    // 填充配置信息，如果没有config_json则使用默认配置
    config: (() => {
      if (job.config_json) {
        try {
          // 如果config_json是字符串，需要解析
          const config = typeof job.config_json === 'string' ? JSON.parse(job.config_json) : job.config_json

          // 确保所有必需的字段都存在，如果不存在则使用默认值
          return {
            disabled: config.disabled || false,
            concurrent_build: config.concurrent_build || false,
            quiet_period: config.quiet_period || 5,
            days_to_keep: config.days_to_keep || -1,
            num_to_keep: config.num_to_keep || -1,
            artifact_days_to_keep: config.artifact_days_to_keep || -1,
            artifact_num_to_keep: config.artifact_num_to_keep || -1,
            scm_type: config.scm_type || 'git',
            git_url: config.git_url || '',
            git_branch: config.git_branch || 'main',
            git_credentials: config.git_credentials || '',
            triggers: {
              scm_polling: config.triggers?.scm_polling || false,
              scm_schedule: config.triggers?.scm_schedule || '',
              build_periodically: config.triggers?.build_periodically || false,
              build_schedule: config.triggers?.build_schedule || '',
              upstream_projects: config.triggers?.upstream_projects || '',
              github_hook: config.triggers?.github_hook || false
            },
            build_environment: {
              delete_workspace: config.build_environment?.delete_workspace || false,
              add_timestamps: config.build_environment?.add_timestamps || false,
              timeout_enabled: config.build_environment?.timeout_enabled || false,
              timeout_minutes: config.build_environment?.timeout_minutes || 20
            },
            build_steps: config.build_steps || [],
            maven_name: config.maven_name || 'Maven',
            pom_file: config.pom_file || 'pom.xml',
            maven_goals: config.maven_goals || 'clean compile package',
            maven_opts: config.maven_opts || '',
            pipeline_script: config.pipeline_script || '',
            post_build_actions: {
              archive_artifacts: config.post_build_actions?.archive_artifacts || '',
              junit_results: config.post_build_actions?.junit_results || '',
              email_notification: config.post_build_actions?.email_notification || false,
              email_recipients: config.post_build_actions?.email_recipients || ''
            }
          }
        } catch (e) {
          console.error('解析config_json失败:', e)
          // 如果解析失败，使用默认配置
        }
      }

      // 默认配置
      return {
        disabled: false,
        concurrent_build: false,
        quiet_period: 5,
        days_to_keep: -1,
        num_to_keep: -1,
        artifact_days_to_keep: -1,
        artifact_num_to_keep: -1,
        scm_type: 'git',
        git_url: '',
        git_branch: 'main',
        git_credentials: '',
        triggers: {
          scm_polling: false,
          scm_schedule: '',
          build_periodically: false,
          build_schedule: '',
          upstream_projects: '',
          github_hook: false
        },
        build_environment: {
          delete_workspace: false,
          add_timestamps: false,
          timeout_enabled: false,
          timeout_minutes: 20
        },
        build_steps: [],
        maven_name: 'Maven',
        pom_file: 'pom.xml',
        maven_goals: 'clean compile package',
        maven_opts: '',
        pipeline_script: '',
        post_build_actions: {
          archive_artifacts: '',
          junit_results: '',
          email_notification: false,
          email_recipients: ''
        }
      }
    })()
  }

  console.log('编辑任务数据:', form.value)
  modalVisible.value = true
}

const closeModal = () => {
  modalVisible.value = false
}

const deleteJob = async (job: any) => {
  try {
    // 使用Element Plus的确认对话框
    await ElMessageBox.confirm(
      `确定要删除任务 "${job.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'glass-message-box'
      }
    )

    const { default: request } = await import('@/utils/request')
    await request({
      url: `/api/jenkins/jenkins-jobs/${job.id}/`,
      method: 'delete'
    })

    ElMessage.success('任务删除成功')
    loadJobs() // 刷新任务列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error)
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

const saveJob = async () => {
  saving.value = true
  try {
    const token = localStorage.getItem('token')
    const url = isEdit.value
      ? `/api/jenkins/jenkins-jobs/${form.value.id}/`
      : '/api/jenkins/jenkins-jobs/'

    const method = isEdit.value ? 'PUT' : 'POST'

    // 准备提交数据，将ID字段转换为后端期望的格式
    const submitData = {
      name: form.value.name,
      description: form.value.description,
      job_type: form.value.job_type,
      project: form.value.project_id,
      environment: form.value.environment_id,
      jenkins_server: form.value.jenkins_server_id,
      gitlab_project_id: form.value.gitlab_project_id || null,
      jenkins_job_name: form.value.jenkins_job_name || form.value.name,
      is_active: form.value.is_active !== undefined ? form.value.is_active : true,
      config_json: form.value.config
    }

    console.log('提交数据:', submitData)

    const { default: request } = await import('@/utils/request')
    await request({
      url,
      method: method.toLowerCase(),
      data: submitData
    })

    // 先重新加载数据，确保页面显示最新内容
    await loadJobs()

    // 然后关闭模态框并显示成功消息
    closeModal()
    ElMessage.success(isEdit.value ? '任务更新成功！' : '任务创建成功！')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(`保存失败: ${error.message}`)
  } finally {
    saving.value = false
  }
}

const syncJobs = async () => {
  try {
    syncing.value = true
    const token = localStorage.getItem('token')

    // 如果选择了特定服务器，同步该服务器的任务
    if (selectedServer.value) {
      const { default: request } = await import('@/utils/request')
      const response = await request({
        url: `/api/jenkins/jenkins-servers/${selectedServer.value}/sync_jobs/`,
        method: 'post'
      })

      const result = response.data

      if (result.success) {
        ElMessage.success(`任务同步成功！同步了 ${result.synced_count} 个任务`)

        // 等待一小段时间确保数据库事务完成，然后刷新任务列表
        setTimeout(async () => {
          await loadJobs()
          console.log('同步后的任务列表:', jobs.value)
          console.log('当前选择的服务器:', selectedServer.value)
          console.log('过滤后的任务:', filteredJobs.value)
        }, 500)
      } else {
        ElMessage.error(`任务同步失败: ${result.message}`)
      }
    } else {
      ElMessage.warning('请先选择Jenkins服务器')
    }
  } catch (error) {
    console.error('同步失败:', error)
    ElMessage.error(`同步失败: ${error.message}`)
  } finally {
    syncing.value = false
  }
}

const triggerBuild = async (job: any) => {
  try {
    // 立即显示构建控制台，使用预估的构建号
    const estimatedBuildNumber = (job.last_build_number || 0) + 1
    ElMessage.success('构建已触发！正在启动...')
    openBuildConsole(job, estimatedBuildNumber)

    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: `/api/jenkins/jenkins-jobs/${job.id}/trigger_build/`,
      method: 'post',
      data: {
        parameters: {} // 可以根据需要添加构建参数
      }
    })

    const result = response.data

    if (result.success) {
      // 如果返回了实际的构建号，更新控制台
      if (result.build_number && result.build_number !== estimatedBuildNumber) {
        currentBuildNumber.value = result.build_number
      }

      // 启动后台构建状态监控
      const actualBuildNumber = result.build_number || estimatedBuildNumber
      startBackgroundBuildCheck(job.id, actualBuildNumber)

      loadJobs() // 刷新任务列表
    } else {
      ElMessage.error(`触发构建失败: ${result.message}`)
      // 关闭控制台
      consoleModalVisible.value = false
    }
  } catch (error) {
    console.error('触发构建失败:', error)
    ElMessage.error(`触发构建失败: ${error.message}`)
    // 关闭控制台
    consoleModalVisible.value = false
  }
}

const onProjectChange = () => {
  console.log('项目变化:', selectedProject.value)
}

const onEnvironmentChange = () => {
  console.log('环境变化:', selectedEnvironment.value)
}

const onServerChange = () => {
  console.log('服务器变化:', selectedServer.value)
}

const onJobTypeChange = () => {
  console.log('任务类型变化:', selectedJobType.value)
}

const getJobTypeDisplay = (jobType: string) => {
  const typeMap = {
    'freestyle': 'Freestyle项目',
    'maven': 'Maven项目',
    'pipeline': 'Pipeline项目'
  }
  return typeMap[jobType] || jobType
}

const getConfigComponent = (jobType: string) => {
  // 根据任务类型返回对应的配置组件名称
  // 这里我们使用动态组件，但实际上所有类型都使用相同的配置表单
  // 因为配置表单内部会根据jobType显示不同的字段
  return 'div' // 暂时返回div，因为配置表单已经内联在模板中
}

const getJobStatusClass = (status: string) => {
  const statusClasses = {
    'SUCCESS': 'job-success',
    'FAILURE': 'job-failure',
    'UNSTABLE': 'job-unstable',
    'ABORTED': 'job-aborted',
    'BUILDING': 'job-building'
  }
  return statusClasses[status] || 'job-unknown'
}

const getEnvClass = (envCode: string) => {
  const envClasses = {
    'dev': 'env-dev',
    'test': 'env-test',
    'uat': 'env-uat',
    'prod': 'env-prod'
  }
  return envClasses[envCode] || 'env-default'
}

const getJobTypeClass = (jobType: string) => {
  const typeClasses = {
    'freestyle': 'type-freestyle',
    'maven': 'type-maven',
    'pipeline': 'type-pipeline'
  }
  return typeClasses[jobType] || 'type-default'
}

const getJobTypeText = (jobType: string) => {
  const typeTexts = {
    'freestyle': 'Freestyle',
    'maven': 'Maven',
    'pipeline': 'Pipeline'
  }
  return typeTexts[jobType] || jobType
}

const getBuildStatusClass = (status: string) => {
  const statusClasses = {
    'SUCCESS': 'status-success job-success',
    'FAILURE': 'status-failure job-failure',
    'UNSTABLE': 'status-unstable job-unstable',
    'ABORTED': 'status-aborted job-aborted',
    'BUILDING': 'status-building job-building',
    'RUNNING': 'status-building job-building'
  }
  return statusClasses[status] || 'status-unknown job-unknown'
}

const getBuildStatusText = (status: string) => {
  const statusTexts = {
    'SUCCESS': '成功',
    'FAILURE': '失败',
    'UNSTABLE': '不稳定',
    'ABORTED': '已中止',
    'BUILDING': '构建中',
    'RUNNING': '构建中'
  }
  return statusTexts[status] || '未知'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadJobs = async () => {
  try {
    console.log('开始重新加载任务列表...')
    const token = localStorage.getItem('token')

    // 构建查询参数
    const params = new URLSearchParams()
    if (selectedProject.value) params.append('project_id', selectedProject.value)
    if (selectedEnvironment.value) params.append('environment_id', selectedEnvironment.value)
    if (selectedServer.value) params.append('jenkins_server_id', selectedServer.value)
    if (selectedJobType.value) params.append('job_type', selectedJobType.value)
    if (searchText.value) params.append('search', searchText.value)

    const url = `/api/jenkins/jenkins-jobs/${params.toString() ? '?' + params.toString() : ''}`

    const { default: request } = await import('@/utils/request')
    const response = await request({
      url,
      method: 'get'
    })

    const data = response.data
    jobs.value = data.results || data
    console.log('任务列表重新加载完成，共', jobs.value.length, '个任务')

    // 检查是否有BUILDING状态的任务，如果有就启动后台监控
    jobs.value.forEach(job => {
      if (job.last_build_status === 'BUILDING' && job.last_build_number) {
        console.log(`检测到构建中的任务: ${job.name}, 构建号: ${job.last_build_number}`)
        startBackgroundBuildCheck(job.id, job.last_build_number)
      }
    })
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error(`加载任务列表失败: ${error.message}`)
  }
}

// 加载项目列表
const loadProjects = async () => {
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: '/api/jenkins/projects/',
      method: 'get'
    })

    const data = response.data
    projects.value = data.results || data
  } catch (error) {
    console.error('加载项目列表失败:', error)
  }
}

// 加载环境列表
const loadEnvironments = async () => {
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: '/api/jenkins/environments/',
      method: 'get'
    })

    const data = response.data
    environments.value = data.results || data
  } catch (error) {
    console.error('加载环境列表失败:', error)
  }
}

// 加载Jenkins服务器列表
const loadJenkinsServers = async () => {
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: '/api/jenkins/jenkins-servers/',
      method: 'get'
    })

    const data = response.data
    jenkinsServers.value = data.results || data
  } catch (error) {
    console.error('加载Jenkins服务器列表失败:', error)
  }
}

// 加载GitLab项目列表
const loadGitLabProjects = async () => {
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: '/api/gitlab/gitlab-projects/',
      method: 'get'
    })

    const data = response.data
    gitlabProjects.value = data.results || data
  } catch (error) {
    console.error('加载GitLab项目列表失败:', error)
  }
}

// 构建控制台相关方法
const openBuildConsole = (job: any, buildNumber: number) => {
  currentBuildJob.value = job
  currentBuildNumber.value = buildNumber
  consoleOutput.value = ''
  buildStatus.value = 'RUNNING'
  buildStartTime.value = new Date().toLocaleString()
  buildDuration.value = 0
  consoleModalVisible.value = true

  // 开始轮询构建日志
  startConsolePolling()
}

const startConsolePolling = () => {
  if (consoleUpdateInterval) {
    clearInterval(consoleUpdateInterval)
  }

  consoleUpdateInterval = setInterval(async () => {
    await fetchBuildConsole()
  }, 2000) // 每2秒更新一次

  // 立即获取一次
  fetchBuildConsole()
}

const fetchBuildConsole = async () => {
  if (!currentBuildJob.value || !currentBuildNumber.value) return

  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: `/api/jenkins/jenkins-jobs/${currentBuildJob.value.id}/console/${currentBuildNumber.value}/`,
      method: 'get'
    })

    const result = response.data
    consoleOutput.value = result.console_output || ''
    buildStatus.value = result.status || 'RUNNING'
    buildDuration.value = result.duration || 0

    // 如果构建完成，停止轮询并更新任务状态
    if (['SUCCESS', 'FAILURE', 'ABORTED', 'UNSTABLE'].includes(buildStatus.value)) {
      console.log('构建完成，状态:', buildStatus.value, '正在更新任务状态...')
      stopConsolePolling()

      // 更新任务的构建状态
      try {
        await updateJobBuildStatus(currentBuildJob.value.id, buildStatus.value, currentBuildNumber.value)
        console.log('任务状态更新成功')
      } catch (error) {
        console.error('更新任务状态失败:', error)
      }

      // 刷新任务列表以更新卡片状态
      setTimeout(() => {
        loadJobs()
      }, 500)
    }

    // 自动滚动到底部
    if (autoScroll.value) {
      nextTick(() => {
        if (consoleOutputRef.value) {
          consoleOutputRef.value.scrollTop = consoleOutputRef.value.scrollHeight
        }
      })
    }
  } catch (error) {
    console.error('获取构建日志失败:', error)
  }
}

const stopConsolePolling = () => {
  if (consoleUpdateInterval) {
    clearInterval(consoleUpdateInterval)
    consoleUpdateInterval = null
  }
}

const closeBuildConsole = () => {
  stopConsolePolling()
  consoleModalVisible.value = false
  currentBuildJob.value = null
  currentBuildNumber.value = null
  consoleOutput.value = ''
}

const toggleAutoScroll = () => {
  autoScroll.value = !autoScroll.value
}

const downloadConsoleLog = () => {
  if (!consoleOutput.value) return

  const blob = new Blob([consoleOutput.value], { type: 'text/plain' })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${currentBuildJob.value?.name}-build-${currentBuildNumber.value}-console.log`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  window.URL.revokeObjectURL(url)
}

// 更新任务构建状态
const updateJobBuildStatus = async (jobId: number, status: string, buildNumber: number) => {
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: `/api/jenkins/jenkins-jobs/${jobId}/`,
      method: 'patch',
      data: {
        last_build_status: status,
        last_build_number: buildNumber,
        last_build_time: new Date().toISOString()
      }
    })

    return response.data
  } catch (error) {
    console.error('更新任务构建状态失败:', error)
    throw error
  }
}

// 后台构建状态检查
const startBackgroundBuildCheck = (jobId: number, buildNumber: number) => {
  // 如果已经有这个任务的检查，先清除
  stopBackgroundBuildCheck(jobId)

  const checkBuildStatus = async () => {
    try {
      const { default: request } = await import('@/utils/request')
      const response = await request({
        url: `/api/jenkins/jenkins-jobs/${jobId}/builds/${buildNumber}/console/`,
        method: 'get'
      })

      const result = response.data

      // 如果构建完成，更新任务状态并停止检查
      if (['SUCCESS', 'FAILURE', 'ABORTED', 'UNSTABLE'].includes(result.status)) {
        console.log(`后台检测到构建完成: Job ${jobId}, Build ${buildNumber}, Status: ${result.status}`)

        // 更新任务状态
        try {
          await updateJobBuildStatus(jobId, result.status, buildNumber)
          console.log('后台任务状态更新成功')
        } catch (error) {
          console.error('后台更新任务状态失败:', error)
        }

        // 刷新任务列表
        loadJobs()

        // 停止检查
        stopBackgroundBuildCheck(jobId)
      }
    } catch (error) {
      console.error('后台构建状态检查失败:', error)
    }
  }

  // 立即检查一次，然后每10秒检查一次
  checkBuildStatus()
  const intervalId = setInterval(checkBuildStatus, 10000)

  backgroundBuildChecks.set(jobId, { buildNumber, intervalId })
  console.log(`开始后台监控构建状态: Job ${jobId}, Build ${buildNumber}`)
}

const stopBackgroundBuildCheck = (jobId: number) => {
  const check = backgroundBuildChecks.get(jobId)
  if (check) {
    clearInterval(check.intervalId)
    backgroundBuildChecks.delete(jobId)
    console.log(`停止后台监控构建状态: Job ${jobId}`)
  }
}

// 构建历史功能
const viewBuilds = async (job: any) => {
  currentJobForBuilds.value = job
  buildsModalVisible.value = true
  await loadBuilds(job.id)
}

const loadBuilds = async (jobId: number) => {
  buildsLoading.value = true
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: `/api/jenkins/jenkins-jobs/${jobId}/builds/`,
      method: 'get'
    })

    const data = response.data
    builds.value = data.results || data
  } catch (error) {
    console.error('加载构建历史失败:', error)
    ElMessage.error('加载构建历史失败')
    builds.value = []
  } finally {
    buildsLoading.value = false
  }
}

const closeBuildsModal = () => {
  buildsModalVisible.value = false
  currentJobForBuilds.value = null
  builds.value = []
}

// 日志查看功能
const viewLogs = async (job: any) => {
  if (!job.last_build_number) {
    ElMessage.warning('该任务还没有构建记录')
    return
  }

  currentLogBuild.value = {
    job: job,
    buildNumber: job.last_build_number
  }
  logModalVisible.value = true
  await loadBuildLog(job.id, job.last_build_number)
}

const viewBuildLog = async (job: any, buildNumber: number) => {
  currentLogBuild.value = {
    job: job,
    buildNumber: buildNumber
  }
  logModalVisible.value = true
  await loadBuildLog(job.id, buildNumber)
}

const loadBuildLog = async (jobId: number, buildNumber: number) => {
  logLoading.value = true
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: `/api/jenkins/jenkins-jobs/${jobId}/console/${buildNumber}/`,
      method: 'get'
    })

    const data = response.data
    logContent.value = data.console_output || '暂无日志内容'
  } catch (error) {
    console.error('加载构建日志失败:', error)
    ElMessage.error('加载构建日志失败')
    logContent.value = '加载日志失败'
  } finally {
    logLoading.value = false
  }
}

const closeLogModal = () => {
  logModalVisible.value = false
  currentLogBuild.value = null
  logContent.value = ''
}

const downloadBuildLog = () => {
  if (!logContent.value || !currentLogBuild.value) return

  const blob = new Blob([logContent.value], { type: 'text/plain' })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${currentLogBuild.value.job.name}-build-${currentLogBuild.value.buildNumber}-log.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  window.URL.revokeObjectURL(url)
}

// 刷新任务列表
const refreshJobs = async () => {
  loading.value = true
  try {
    await loadJobs()
  } finally {
    loading.value = false
  }
}

// 导出任务列表
const exportJobs = async () => {
  try {
    const { default: request } = await import('@/utils/request')
    const response = await request({
      url: '/api/jenkins/jenkins-jobs/export/',
      method: 'get',
      responseType: 'blob'
    })

    const blob = response.data
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `jenkins_jobs_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    ElMessage.success('任务列表导出成功')
  } catch (error) {
    console.error('导出任务列表失败:', error)
    ElMessage.error('导出任务列表失败')
  }
}

// 生命周期
onMounted(() => {
  loadJobs()
  loadProjects()
  loadEnvironments()
  loadJenkinsServers()
  loadGitLabProjects()
})

// 页面卸载时清理所有后台检查
onUnmounted(() => {
  // 清理所有后台构建检查
  for (const [jobId] of backgroundBuildChecks) {
    stopBackgroundBuildCheck(jobId)
  }

  // 清理控制台轮询
  if (consoleUpdateInterval) {
    clearInterval(consoleUpdateInterval)
  }
})
</script>

<style scoped>
/* 使用与Zabbix管理页面完全相同的样式 */
.ansible-audit-container {
  min-height: 100vh;
  background: linear-gradient(
    135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  overflow-x: hidden;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  z-index: -1;
}

.glass-container {
  background: rgba(164, 244, 186, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  color: #fff;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.project-env-selector {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.selector-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 180px;
}

.selector-group label {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  font-weight: 500;
}

/* 这个样式已经移动到下面，避免重复 */

.jobs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));
  gap: 20px;
}

.job-card {
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
}

.job-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
  border-color: rgba(164, 244, 186, 0.4);
}

.job-card.job-success {
  border-left: 4px solid #51cf66;
}

.job-card.job-failure {
  border-left: 4px solid #ff6b6b;
}

.job-card.job-unstable {
  border-left: 4px solid #ffd43b;
}

.job-card.job-aborted {
  border-left: 4px solid #868e96;
}

.job-card.job-building {
  border-left: 4px solid #339af0;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.7; }
  100% { opacity: 1; }
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.job-name {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;
}

.job-description {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

.job-badges {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.project-badge {
  background: rgba(164, 244, 186, 0.2);
  color: #a4f4ba;
  border: 1px solid rgba(164, 244, 186, 0.3);
}

.env-badge {
  border: 1px solid;
}

.env-dev {
  background: rgba(74, 222, 128, 0.2);
  color: #4ade80;
  border-color: rgba(74, 222, 128, 0.3);
}

.env-test {
  background: rgba(251, 191, 36, 0.2);
  color: #fbbf24;
  border-color: rgba(251, 191, 36, 0.3);
}

.env-uat {
  background: rgba(168, 85, 247, 0.2);
  color: #a855f7;
  border-color: rgba(168, 85, 247, 0.3);
}

.env-prod {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
  border-color: rgba(239, 68, 68, 0.3);
}

.env-default {
  background: rgba(156, 163, 175, 0.2);
  color: #9ca3af;
  border-color: rgba(156, 163, 175, 0.3);
}

.type-badge {
  border: 1px solid;
}

.type-freestyle {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
  border-color: rgba(34, 197, 94, 0.3);
}

.type-maven {
  background: rgba(249, 115, 22, 0.2);
  color: #f97316;
  border-color: rgba(249, 115, 22, 0.3);
}

.type-pipeline {
  background: rgba(99, 102, 241, 0.2);
  color: #6366f1;
  border-color: rgba(99, 102, 241, 0.3);
}

.type-default {
  background: rgba(156, 163, 175, 0.2);
  color: #9ca3af;
  border-color: rgba(156, 163, 175, 0.3);
}

.job-details {
  margin-bottom: 16px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-row .label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}

.detail-row .value {
  color: #fff;
  font-size: 14px;
}

.build-status {
  font-weight: 600;
}

.status-success {
  color: #51cf66;
}

.status-failure {
  color: #ff6b6b;
}

.status-unstable {
  color: #ffd43b;
}

.status-aborted {
  color: #868e96;
}

.status-building {
  color: #339af0;
}

.status-unknown {
  color: rgba(255, 255, 255, 0.5);
}

.job-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.glass-button {
  background: rgba(164, 244, 186, 0.2);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  color: #fff;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.glass-button:hover {
  background: rgba(164, 244, 186, 0.3);
  border-color: rgba(164, 244, 186, 0.5);
  transform: translateY(-2px);
}

.glass-button.primary {
  background: rgba(164, 244, 186, 0.3);
  border-color: rgba(164, 244, 186, 0.5);
}

.glass-button.small {
  padding: 4px 8px;
  font-size: 12px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.7);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state h3 {
  color: #fff;
  margin-bottom: 8px;
}

.empty-state p {
  margin-bottom: 24px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
}

.glass-modal {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.modal-content {
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.modal-header h3 {
  color: #fff;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #fff;
}

.job-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  font-weight: 500;
}

.glass-input {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  padding: 12px;
  color: #fff;
  font-size: 14px;
  transition: all 0.3s ease;
  resize: vertical;
}

.glass-input:focus {
  outline: none;
  border-color: rgba(164, 244, 186, 0.5);
  background: rgba(164, 244, 186, 0.15);
}

.glass-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 8px;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

.audit-content {
  position: relative;
  z-index: 10;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section h1 {
  color: rgba(255, 255, 255, 0.95);
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.title-section h1 i {
  color: #a4f4ba;
  margin-right: 12px;
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #a4f4ba;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.search-filters {
  margin-bottom: 30px;
  padding: 24px;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  border-radius: 12px;
  gap: 24px;
  flex-wrap: wrap;
}

.toolbar-left {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
  min-width: 0;
  flex: 0 0 auto;
}

.toolbar-right {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
  min-width: 0;
  flex: 1 1 auto;
  justify-content: flex-start;
}

.search-group {
  width: 280px;
  flex: 0 0 280px;
}

.filter-group {
  width: 180px;
  flex: 0 0 180px;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .search-filters {
    flex-direction: column;
    align-items: stretch;
    gap: 20px;
  }

  .toolbar-left {
    justify-content: flex-start;
  }

  .toolbar-right {
    justify-content: flex-start;
    gap: 16px;
  }

  .search-group {
    width: 280px;
    flex: 0 0 280px;
  }

  .filter-group {
    width: 180px;
    flex: 0 0 180px;
  }
}

/* 搜索输入框和选择器样式优化 */
.glass-input {
  background: rgba(164, 244, 186, 0.08) !important;
  border: 1px solid rgba(164, 244, 186, 0.25) !important;
  border-radius: 8px !important;
  padding: 10px 14px !important;
  color: #fff !important;
  font-size: 14px !important;
  transition: all 0.3s ease !important;
  width: 100% !important;
  min-height: 40px !important;
  box-sizing: border-box !important;
  backdrop-filter: blur(10px) !important;
}

.glass-input:focus {
  outline: none !important;
  border-color: rgba(164, 244, 186, 0.5) !important;
  background: rgba(164, 244, 186, 0.12) !important;
  box-shadow: 0 0 0 2px rgba(164, 244, 186, 0.1) !important;
}

.glass-input::placeholder {
  color: rgba(255, 255, 255, 0.6) !important;
}

/* 原生select的glass样式 */
select.glass-select {
  background: rgba(164, 244, 186, 0.08) !important;
  border: 1px solid rgba(164, 244, 186, 0.25) !important;
  border-radius: 8px !important;
  padding: 10px 14px !important;
  color: #fff !important;
  font-size: 14px !important;
  transition: all 0.3s ease !important;
  width: 100% !important;
  min-height: 40px !important;
  box-sizing: border-box !important;
  backdrop-filter: blur(10px) !important;
  cursor: pointer !important;
}

/* Element Plus el-select的glass样式 */
.glass-select .el-select__wrapper {
  background: rgba(164, 244, 186, 0.08) !important;
  border: 1px solid rgba(164, 244, 186, 0.25) !important;
  border-radius: 8px !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
}

.glass-select .el-input__inner {
  color: #fff !important;
  background: transparent !important;
}

.glass-select .el-select__placeholder {
  color: rgba(255, 255, 255, 0.6) !important;
}

.glass-select:focus {
  outline: none !important;
  border-color: rgba(164, 244, 186, 0.5) !important;
  background: rgba(164, 244, 186, 0.12) !important;
  box-shadow: 0 0 0 2px rgba(164, 244, 186, 0.1) !important;
}

.glass-select option {
  background: rgba(30, 30, 30, 0.95) !important;
  color: #fff !important;
  padding: 8px !important;
  border: none !important;
}

/* 工具栏按钮样式优化 */
.toolbar-left .glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 10px 18px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
  white-space: nowrap !important;
  min-height: 40px !important;
  display: flex !important;
  align-items: center !important;
  gap: 8px !important;
}

.toolbar-left .glass-button:hover {
  background: rgba(164, 244, 186, 0.25) !important;
  border-color: rgba(164, 244, 186, 0.5) !important;
  color: #ffffff !important;
  box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  transform: translateY(-1px) !important;
}

.toolbar-left .glass-button i {
  color: #00eaff !important;
}

.toolbar-left .glass-button.refresh-button {
  background: rgba(138, 43, 226, 0.2) !important;
  border-color: rgba(138, 43, 226, 0.4) !important;
}

.toolbar-left .glass-button.refresh-button:hover {
  background: rgba(138, 43, 226, 0.3) !important;
  border-color: rgba(138, 43, 226, 0.6) !important;
  box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
}

.toolbar-left .glass-button.refresh-button i {
  color: #8a2be2 !important;
}

.toolbar-left .glass-button.sync-button {
  background: rgba(59, 130, 246, 0.2) !important;
  border-color: rgba(59, 130, 246, 0.4) !important;
  color: #ffffff !important;
}

.toolbar-left .glass-button.sync-button:hover {
  background: rgba(59, 130, 246, 0.3) !important;
  border-color: rgba(59, 130, 246, 0.6) !important;
  box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
}

.toolbar-left .glass-button.sync-button i {
  color: #3b82f6 !important;
}

.toolbar-left .glass-button.add-button {
  background: rgba(34, 197, 94, 0.2) !important;
  border-color: rgba(34, 197, 94, 0.4) !important;
  color: #ffffff !important;
}

.toolbar-left .glass-button.add-button:hover {
  background: rgba(34, 197, 94, 0.3) !important;
  border-color: rgba(34, 197, 94, 0.6) !important;
  box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
}

.toolbar-left .glass-button.add-button i {
  color: #22c55e !important;
}

.toolbar-left .glass-button.import-button {
  background: rgba(6, 182, 212, 0.2) !important;
  border-color: rgba(6, 182, 212, 0.4) !important;
  color: #ffffff !important;
}

.toolbar-left .glass-button.import-button:hover {
  background: rgba(6, 182, 212, 0.3) !important;
  border-color: rgba(6, 182, 212, 0.6) !important;
  box-shadow: 0 4px 16px rgba(6, 182, 212, 0.3) !important;
}

.toolbar-left .glass-button.import-button i {
  color: #06b6d4 !important;
}

.toolbar-left .glass-button.delete-button {
  background: rgba(239, 68, 68, 0.2) !important;
  border-color: rgba(239, 68, 68, 0.4) !important;
  color: #ffffff !important;
}

.toolbar-left .glass-button.delete-button:hover {
  background: rgba(239, 68, 68, 0.3) !important;
  border-color: rgba(239, 68, 68, 0.6) !important;
  box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3) !important;
}

.toolbar-left .glass-button.delete-button i {
  color: #ef4444 !important;
}

/* Element Plus 选择器样式覆盖 - 使用超透明样式 */
:deep(.el-select) {
  .el-input__wrapper {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    border-radius: 8px !important;
    box-shadow: none !important;
    transition: all 0.3s ease !important;
  }

  .el-input__inner {
    background: transparent !important;
    color: rgba(255, 255, 255, 0.9) !important;
  }

  .el-input__suffix {
    color: rgba(255, 255, 255, 0.6) !important;
  }

  .el-select__placeholder {
    color: rgba(255, 255, 255, 0.5) !important;
  }

  &:hover .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
    background: rgba(164, 244, 186, 0.15) !important;
  }

  &.is-focused .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
    background: rgba(164, 244, 186, 0.15) !important;
  }
}

:deep(.el-select-dropdown) {
  background: rgba(20, 20, 20, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  border-radius: 8px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
  transform: translateX(0) !important;
  left: auto !important;
}

:deep(.el-select-dropdown__item) {
  color: rgba(255, 255, 255, 0.9) !important;
  background: transparent !important;
  transition: all 0.3s ease !important;

  &:hover {
    background: rgba(164, 244, 186, 0.1) !important;
    color: #ffffff !important;
  }

  &.is-selected {
    background: rgba(164, 244, 186, 0.2) !important;
    color: #ffffff !important;
    font-weight: 500 !important;
  }
}

/* 修复Element Plus下拉菜单定位偏移问题 */
:deep(.el-popper.is-pure) {
  transform: none !important;
}

:deep(.el-popper[data-popper-placement^="bottom"]) {
  transform: translateX(0) translateY(4px) !important;
}

/* 全局修复所有el-select下拉菜单的定位 */
:deep(.el-select-dropdown.el-popper) {
  transform: translateX(0) !important;
  margin-left: 0 !important;
}

/* 特别针对构建步骤中的下拉菜单 */
.step-header {
  position: relative;
}

.step-header .el-select {
  position: static;
}

/* 强制修复所有Element Plus下拉菜单的定位偏移 */
:deep(.el-select-dropdown) {
  margin-left: 0 !important;
  transform: translateX(0) !important;
}

:deep(.el-popper) {
  margin-left: 0 !important;
}

/* 如果还有偏移，使用更强制的修复 */
:deep(.el-select-dropdown.el-popper[data-popper-placement]) {
  transform: translateX(0) translateY(4px) !important;
  left: var(--el-popper-arrow-offset, 0) !important;
}

/* Element Plus 下拉菜单样式覆盖 - 透明玻璃效果 */
:deep(.glass-dropdown) {
  background: rgba(20, 20, 40, 0.95) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  -webkit-backdrop-filter: blur(20px) saturate(150%) !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
  border-radius: 12px !important;
  z-index: 9999 !important;

  .el-select-dropdown__item {
    background: transparent !important;
    color: #fff !important;
    padding: 10px 16px !important;
    margin: 2px 6px !important;
    border-radius: 8px !important;
    transition: all 0.3s ease !important;
    font-size: 14px !important;
    font-weight: 500 !important;

    &:hover {
      background: rgba(164, 244, 186, 0.2) !important;
      color: #fff !important;
      transform: translateX(2px) !important;
      box-shadow: 0 2px 8px rgba(0, 234, 255, 0.2) !important;
    }

    &.is-selected {
      background: rgba(0, 234, 255, 0.3) !important;
      color: #fff !important;
      font-weight: 600 !important;
    }

    &.is-disabled {
      color: rgba(255, 255, 255, 0.3) !important;
      background: transparent !important;
      cursor: not-allowed !important;

      &:hover {
        background: transparent !important;
        transform: none !important;
        box-shadow: none !important;
      }
    }

    i {
      margin-right: 6px !important;
      color: rgba(0, 234, 255, 0.8) !important;
    }
  }

  .el-select-dropdown__item--divided {
    border-top: 1px solid rgba(164, 244, 186, 0.3) !important;
    margin-top: 6px !important;
    padding-top: 12px !important;
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    border-radius: 8px !important;
    box-shadow: none !important;
  }

  .el-input__inner {
    background: transparent !important;
    color: #fff !important;
  }

  &:hover .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
  }

  &.is-focus .el-input__wrapper {
    border-color: rgba(164, 244, 186, 0.5) !important;
    background: rgba(164, 244, 186, 0.15) !important;
  }
}

:deep(.el-select-dropdown) {
  background: rgba(20, 20, 20, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  border-radius: 8px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-select-dropdown__item) {
  color: rgba(255, 255, 255, 0.9) !important;
  background: transparent !important;
  transition: all 0.3s ease !important;

  &:hover {
    background: rgba(164, 244, 186, 0.1) !important;
    color: rgba(255, 255, 255, 1) !important;
  }

  &.is-selected {
    background: rgba(164, 244, 186, 0.2) !important;
    color: rgba(255, 255, 255, 1) !important;
  }
}

/* 构建控制台样式 */
.console-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(5px);
}

.console-modal {
  width: 90vw;
  height: 80vh;
  background: #1e1e1e;
  border-radius: 8px;
  border: 1px solid #333;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
  overflow: hidden;
}

.console-header {
  background: #2d2d2d;
  padding: 12px 16px;
  border-bottom: 1px solid #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
}

.console-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.console-title i {
  color: #4CAF50;
}

.build-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  text-transform: uppercase;
}

.build-status.job-success {
  background: #4CAF50;
  color: white;
}

.build-status.job-failure {
  background: #f44336;
  color: white;
}

.build-status.job-building {
  background: #2196F3;
  color: white;
  animation: pulse 2s infinite;
}

.build-status.job-unstable {
  background: #FF9800;
  color: white;
}

.build-status.job-aborted {
  background: #9E9E9E;
  color: white;
}

.console-controls {
  display: flex;
  gap: 8px;
}

.console-btn {
  background: transparent;
  border: 1px solid #555;
  color: #ccc;
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.console-btn:hover {
  background: #444;
  border-color: #777;
  color: #fff;
}

.console-btn.active {
  background: #4CAF50;
  border-color: #4CAF50;
  color: white;
}

.console-btn.close-btn:hover {
  background: #f44336;
  border-color: #f44336;
  color: white;
}

.console-info {
  background: #252525;
  padding: 8px 16px;
  border-bottom: 1px solid #333;
  color: #ccc;
  font-size: 12px;
  display: flex;
  gap: 20px;
}

.console-output {
  flex: 1;
  background: #1e1e1e;
  color: #f0f0f0;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  overflow-y: auto;
  padding: 16px;
  white-space: pre-wrap;
  word-break: break-all;
}

.console-output pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.console-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #888;
  gap: 8px;
}

.console-loading i {
  font-size: 18px;
}

/* 滚动条样式 */
.console-output::-webkit-scrollbar {
  width: 8px;
}

.console-output::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.console-output::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 4px;
}

.console-output::-webkit-scrollbar-thumb:hover {
  background: #777;
}

/* 动画 */
@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

/* 构建历史样式 */
.builds-list {
  max-height: 500px;
  overflow-y: auto;
  padding: 15px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.build-card {
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.build-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(164, 244, 186, 0.2);
  border-color: rgba(164, 244, 186, 0.5);
}

.build-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: linear-gradient(135deg, rgba(164, 244, 186, 0.1), rgba(164, 244, 186, 0.05));
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.build-number {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #a4f4ba;
}

.number-text {
  color: #a4f4ba;
  font-size: 20px;
}

.build-status .status-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-icon {
  font-size: 8px;
}

/* 状态徽章颜色 */
.status-success {
  background: rgba(46, 204, 113, 0.2);
  border: 1px solid rgba(46, 204, 113, 0.4);
  color: #2ecc71;
}

.status-success .status-icon {
  color: #2ecc71;
}

.status-failure {
  background: rgba(231, 76, 60, 0.2);
  border: 1px solid rgba(231, 76, 60, 0.4);
  color: #e74c3c;
}

.status-failure .status-icon {
  color: #e74c3c;
}

.status-building {
  background: rgba(52, 152, 219, 0.2);
  border: 1px solid rgba(52, 152, 219, 0.4);
  color: #3498db;
}

.status-building .status-icon {
  color: #3498db;
}

.status-unstable {
  background: rgba(243, 156, 18, 0.2);
  border: 1px solid rgba(243, 156, 18, 0.4);
  color: #f39c12;
}

.status-unstable .status-icon {
  color: #f39c12;
}

.status-aborted {
  background: rgba(149, 165, 166, 0.2);
  border: 1px solid rgba(149, 165, 166, 0.4);
  color: #95a5a6;
}

.status-aborted .status-icon {
  color: #95a5a6;
}

.build-content {
  padding: 16px 20px;
}

.build-info-row {
  margin-bottom: 12px;
}

.build-info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-icon {
  color: #a4f4ba;
  width: 16px;
  text-align: center;
}

.info-label {
  color: rgba(255, 255, 255, 0.8);
  font-size: 13px;
  min-width: 70px;
  font-weight: 500;
}

.info-value {
  color: #fff;
  font-size: 13px;
  font-weight: 600;
}

.build-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  padding: 12px 20px;
  background: rgba(164, 244, 186, 0.05);
  border-top: 1px solid rgba(164, 244, 186, 0.1);
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 24px;
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(5px);
  color: #fff;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  min-width: 120px;
  height: 40px;
}

.action-btn:hover {
  background: rgba(164, 244, 186, 0.2);
  border-color: rgba(164, 244, 186, 0.5);
  transform: translateY(-1px);
}

/* 构建历史弹窗中的日志按钮样式 - 确保使用action-btn的完整样式 */
.glass-modal .action-btn.log-btn {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 8px !important;
  padding: 12px 24px !important;
  background: rgba(164, 244, 186, 0.05) !important;
  border: 1px solid rgba(164, 244, 186, 0.2) !important;
  border-radius: 8px !important;
  color: #a4f4ba !important;
  cursor: pointer !important;
  transition: all 0.3s ease !important;
  font-size: 14px !important;
  white-space: nowrap !important;
  min-width: 120px !important;
  height: 40px !important;
}

.glass-modal .action-btn.log-btn:hover {
  background: rgba(52, 152, 219, 0.1) !important;
  border-color: rgba(52, 152, 219, 0.3) !important;
  color: #3498db !important;
  transform: translateY(-1px) !important;
}

.console-btn:hover {
  background: rgba(155, 89, 182, 0.1);
  border-color: rgba(155, 89, 182, 0.3);
  color: #9b59b6;
}

/* 日志查看样式 */
.log-modal {
  width: 90vw;
  height: 80vh;
  background: #1e1e1e;
  border-radius: 8px;
  border: 1px solid #333;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
  overflow: hidden;
}

.log-header {
  background: #2d2d2d;
  padding: 12px 16px;
  border-bottom: 1px solid #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
}

.log-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.log-title i {
  color: #4CAF50;
}

.log-controls {
  display: flex;
  gap: 8px;
}

.log-controls .log-btn {
  background: transparent;
  border: 1px solid #555;
  color: #ccc;
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.log-controls .log-btn:hover {
  background: #444;
  border-color: #777;
  color: #fff;
}

.log-controls .log-btn.close-btn:hover {
  background: #f44336;
  border-color: #f44336;
  color: white;
}

.log-content {
  flex: 1;
  background: #1e1e1e;
  color: #f0f0f0;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  overflow-y: auto;
  padding: 16px;
}

.log-text {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.log-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #888;
  gap: 8px;
}

.log-loading i {
  font-size: 18px;
}

/* 滚动条样式 */
.builds-list::-webkit-scrollbar,
.log-content::-webkit-scrollbar {
  width: 8px;
}

.builds-list::-webkit-scrollbar-track,
.log-content::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.builds-list::-webkit-scrollbar-thumb,
.log-content::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 4px;
}

.builds-list::-webkit-scrollbar-thumb:hover,
.log-content::-webkit-scrollbar-thumb:hover {
  background: #777;
}

/* Jenkins创建任务样式 */
.jenkins-create-modal {
  max-width: 900px;
  max-height: 90vh;
}

/* 任务类型选择 */
.type-selection-content {
  padding: 20px 0;
}

.selection-hint {
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  margin-bottom: 30px;
  text-align: center;
}

.job-types-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.job-type-card {
  background: rgba(164, 244, 186, 0.05);
  border: 2px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  padding: 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.job-type-card:hover {
  border-color: rgba(164, 244, 186, 0.4);
  background: rgba(164, 244, 186, 0.1);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(164, 244, 186, 0.2);
}

.job-type-card.active {
  border-color: rgba(164, 244, 186, 0.6);
  background: rgba(164, 244, 186, 0.15);
  box-shadow: 0 0 20px rgba(164, 244, 186, 0.3);
}

.job-type-card .type-icon {
  font-size: 48px;
  color: #a4f4ba;
  margin-bottom: 16px;
}

.job-type-card h4 {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 12px 0;
}

.job-type-card p {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

/* 任务配置表单 */
.jenkins-config-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.config-section {
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(164, 244, 186, 0.03);
  border: 1px solid rgba(164, 244, 186, 0.1);
  border-radius: 8px;
}

.section-title {
  color: #a4f4ba;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 20px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  color: #00eaff;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row:last-child {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }
}

/* 返回按钮 */
.back-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 18px;
  cursor: pointer;
  padding: 4px 8px;
  margin-right: 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.back-btn:hover {
  color: #a4f4ba;
  background: rgba(164, 244, 186, 0.1);
}

/* 新增配置表单样式 */
.config-section {
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.section-title {
  color: #a4f4ba;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  font-size: 18px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 15px;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgba(255, 255, 255, 0.9);
  cursor: pointer;
  font-size: 14px;
}

.glass-checkbox {
  width: 16px;
  height: 16px;
  accent-color: #a4f4ba;
}

.schedule-input,
.timeout-input,
.email-input {
  margin-top: 8px;
  font-size: 13px;
}

.trigger-options,
.build-env-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.build-steps {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.build-step {
  padding: 15px;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(164, 244, 186, 0.1);
  border-radius: 6px;
}

.step-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.step-type {
  flex: 1;
}

.add-step {
  align-self: flex-start;
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  color: #a4f4ba;
}

.add-step:hover {
  background: rgba(164, 244, 186, 0.2);
}

/* 删除按钮样式 */
.glass-button.danger {
  background: rgba(255, 77, 77, 0.1);
  border: 1px solid rgba(255, 77, 77, 0.3);
  color: #ff4d4d;
}

.glass-button.danger:hover {
  background: rgba(255, 77, 77, 0.2);
  border-color: rgba(255, 77, 77, 0.5);
}

/* 确认对话框样式 */
.glass-message-box {
  background: rgba(0, 0, 0, 0.8) !important;
  backdrop-filter: blur(10px) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  border-radius: 8px !important;
}

.glass-message-box .el-message-box__header {
  background: transparent !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2) !important;
}

.glass-message-box .el-message-box__title {
  color: #a4f4ba !important;
}

.glass-message-box .el-message-box__content {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

.glass-message-box .el-button--primary {
  background: rgba(255, 77, 77, 0.8) !important;
  border-color: rgba(255, 77, 77, 0.8) !important;
}

.glass-message-box .el-button--default {
  background: rgba(164, 244, 186, 0.1) !important;
  border-color: rgba(164, 244, 186, 0.3) !important;
  color: #a4f4ba !important;
}

.pipeline-script {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.git-config {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid rgba(164, 244, 186, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .jenkins-config-form {
    padding: 15px;
  }

  .config-section {
    padding: 15px;
    margin-bottom: 20px;
  }
}

/* 最终修复：Element Plus下拉菜单定位偏移问题 - 最高优先级 */
:deep(.el-select-dropdown),
:deep(.el-popper.is-pure),
:deep(.el-popper[data-popper-placement]),
:deep(.el-select-dropdown.el-popper),
:deep(.el-select-dropdown.el-popper.is-pure) {
  transform: translateX(0) translateY(4px) !important;
  margin-left: 0 !important;
  left: auto !important;
  position: absolute !important;
}

/* 针对特定容器的修复 */
.step-header :deep(.el-select-dropdown),
.form-group :deep(.el-select-dropdown),
.job-config-form :deep(.el-select-dropdown) {
  transform: translateX(0) translateY(4px) !important;
  margin-left: 0 !important;
  left: 0 !important;
}

/* 强制重置所有可能的偏移 */
:deep(.el-popper) {
  margin-left: 0 !important;
  margin-right: 0 !important;
}
</style>
